import { createRouter, createWebHistory } from 'vue-router'

// 定义auth对象用于登录状态检查
const auth = {
  isLoggedIn() {
    return !!localStorage.getItem('token');
  }
}

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path: "/", redirect: '/home' },
    {
      path: "/home", name: "home", components: {
        default: () => import("@/views/HomeView/HomeView.vue"),
        footer: () => import('@/components/FooterCom.vue')
      }
    },
    {
      path: "/kind", name: "kind", components: {
        default: () => import("@/views/KindView/KindView.vue"),
        footer: () => import('@/components/FooterCom.vue')
      }
    },
    {
      path: "/cart", name: "cart", components: {
        default: () => import("@/views/CartView/CartView.vue"),
        footer: () => import('@/components/FooterCom.vue')
      }
    },
    {
      path: "/my", name: "my", components: {
        default: () => import("@/views/MyView/MyView.vue"),
        footer: () => import('@/components/FooterCom.vue')
      }
    },
    { path: '/detail/:proid', name: 'detail', component: () => import("@/views/Detail/DetailView.vue") },
    {
      path: '/register', name: 'register', components: {
        default: () => import('@/views/register/RegisterView.vue')
      }, children: [
        { path: "/register/", redirect: "/register/checktel" },
        { path: 'checktel', component: () => import('@/views/register/components/CheckTel.vue') },
        { path: 'sendmsg', component: () => import('@/views/register/components/SendMsg.vue') },
        { path: 'sendpass', component: () => import('@/views/register/components/SendPass.vue') }
      ]
    },
    {
      path: '/login', name: 'login', components: {
        default: () => import('@/views/register/Login.vue')
      }
    }

    
  ],
})



router.beforeEach((to, from) => {
  // 而不是去检查每条路由记录
  // to.matched.some(record => record.meta.requiresAuth)
  if (to.meta.requiresAuth && !auth.isLoggedIn()) {
    // 此路由需要授权，请检查是否已登录
    // 如果没有，则重定向到登录页面
    return {
      path: '/login',
      // 保存我们所在的位置，以便以后再来
      query: { redirect: to.fullPath },
    }
  }
})
export default router
